package com.woniuxy.rbac.web.api;

import com.woniuxy.rbac.entity.ResponseResult;
import com.woniuxy.rbac.entity.User;
import com.woniuxy.rbac.service.UserService;
import com.woniuxy.rbac.shiro.SysUsernamePasswordToken;
import com.woniuxy.rbac.utils.Audience;
import com.woniuxy.rbac.utils.JwtUtil;
import com.woniuxy.rbac.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * 用户操作Controller类
 *
 * @Auther: 老谭（<a href="http://www.woniuxy.com">蜗牛学苑</a>）
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public ResponseResult add(@RequestBody UserVO userVO) {
        userService.add(userVO.getUser(), userVO.getPermIds(), userVO.getRoleIds());
        return ResponseResult.SUCCESS;
    }

    @GetMapping("getall")
    public String getAll(Model model) {
        model.addAttribute("users", userService.getAll());
        return "user/user_list";
    }

    @GetMapping("/del/{id}")
    public String del(@PathVariable int id) {
        userService.delById(id);
        return "redirect:/user/getall"; //前台重定向
    }

    @Autowired
    private Audience audience;

    /**
     * 用户登录
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user) {
        SysUsernamePasswordToken token = new SysUsernamePasswordToken(user.getAccount(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            User u = (User) subject.getPrincipal();
            String jwt = JwtUtil.createJwt(u.getId(), u.getAccount(), audience);
            return new ResponseResult(jwt);
        } catch (UnknownAccountException uae) {
            return new ResponseResult(501, "no account");
        } catch (IncorrectCredentialsException ice) {
            return new ResponseResult(502, "invalid password");
        }catch (AuthenticationException e){
            return new ResponseResult(502, "AuthenticationException Fail");
        }
    }

    @GetMapping("test")
    @ResponseBody
    public ResponseResult test(@RequestHeader("token") String token) {
        log.debug("token:{}", token);
        //解析出来id或account
        return ResponseResult.SUCCESS;
    }


}
